<template>
  <el-dialog title="修改密码" :visible.sync="dialogvisible" :before-close="handleClose">
    <el-form
      :model="p"
      :rules="rules"
      class="form"
      label-position="right"
      label-width="80px"
      ref="form"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input type="password" v-model="p.oldPassword" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="p.password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="p.confirmPassword" />
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" plain type="primary">修改</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {};
      }
    },
    visible: false
  },
  watch: {
    visible: function() {
      let that = this;
      that.dialogvisible = this.visible;
    }
  },
  data() {
    return {
      dialogvisible: false,
      p: {
        oldPassword: "",
        password: "",
        confirmPassword: ""
      },
      rules: {
        oldPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "新密码不能为空！", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度必须在6-20位之间",
            trigger: "blur"
          }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.p.password !== value) {
                callback("确认密码和新密码不一致");
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$https.postXform("/updatePassword", { ...this.p }).then(res => {
            if (res.data.data) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.$emit("update:visible", false);
              this.$refs.form.clearValidate();
              this.$refs.form.resetFields();
            }
          });
        } else {
          return false;
        }
      });
    },
    handleClose(done) {
      this.$emit("update:visible", false);
      done();
    }
  }
};
</script>
